09. Add URIs to the Contract

Add URIs to the Contract

As we just saw, designing and using the proper URI is important for helping us get the information we need from each table.

Now let’s take a look at how to add the URI to our code in PetContract.java.
Recall that the 3 parts of a content URI - scheme, content authority, type of data:

Structure of Content URI

Add URIs to the Contract

Since some of these components will be reusable and won’t change, it’s helpful to represent them as constants.

Now comes the question of where best to store these constants. Recall that we previously stored all data-related constants in the Contract class, so this is an ideal place to store our URI constant information as well.

CONTENT_AUTHORITY

Let’s start with the Content Authority which is used to help identify the Content Provider which we’d setup before in the AndroidManifest tag:

 <provider
      android:name=”.data.PetProvider”
      android:authorities=”com.example.android.pets”
      android:exported=”false” />

In PetContract.java, we set this up as a string constant whose value is the same as that from the AndroidManifest:

 public static final String CONTENT_AUTHORITY = "com.example.android.pets";

BASE_CONTENT_URI

Next, we concatenate the CONTENT_AUTHORITY constant with the scheme “content://” we will create the BASE_CONTENT_URI which will be shared by every URI associated with PetContract:

 "content://" + CONTENT_AUTHORITY

To make this a usable URI, we use the parse method which takes in a URI string and returns a Uri.

 public static final Uri BASE_CONTENT_URI = Uri.parse("content://" + CONTENT_AUTHORITY);

PATH_TableName

This constants stores the path for each of the tables which will be appended to the base content URI.

 public static final String PATH_PETS = "pets";

Complete CONTENT_URI

Lastly, inside each of the Entry classes in the contract, we create a full URI for the class as a constant called CONTENT_URI.
The Uri.withAppendedPath() method appends the BASE_CONTENT_URI (which contains the scheme and the content authority) to the path segment.

 public static final Uri CONTENT_URI = Uri.withAppendedPath(BASE_CONTENT_URI, PATH_PETS);

After adding these constants, the PetContract.java class will look like this.

Your Task:

Update your PetContract.java class to match our code by copying over the first 3 constants OUTSIDE of PetEntry.

Then, copy the CONTENT_URI constant inside PetEntry.

If you want to check out the code diff for this step, check out this GitHub link.